/**
 * Created by xmh on 2017/4/29.
 */

import {Injectable} from '@angular/core';

@Injectable()
export class StorageService {

  constructor() {
    //console.log('Hello HttpService Provider');
  }

  //存放到 localStorage，不主动删除将永远存在, localStorage只支持string
  setLocal(key: string, value: any) {
    if (value) {
      value = JSON.stringify(value);
    }
    localStorage.setItem(key, value); //可以是对象
  }

  //从localStorage 获取值,
  getLocal(key: string){
    let value: string = localStorage.getItem(key);
    if (value && value != "undefined" && value != "null") {
      return JSON.parse(value);
    }

    return null;
  }

  //localStorage 删除某个key
  delLocal(key: string) {
    localStorage.removeItem(key);
  }

  //存放到 sessionStorage，浏览器关闭就没有了
  setSession(key: string, value: any) {
    if (value) {
      value = JSON.stringify(value);
    }
    sessionStorage.setItem(key, value);
  }

  //sessionStorage 获取值
  getSession(key: string){
    let value: string = sessionStorage.getItem(key);
    if (value && value != "undefined" && value != "null") {
      return JSON.parse(value);
    }
    return null;
  }

  //sessionStorage 删除某个key
  delSession(key: string) {
    sessionStorage.removeItem(key);
  }

  //清空 sessionStorage
  clearSession() {
    sessionStorage.clear();
  }
}
